<template>
  <view class="quick_bill">
    <view class="block_box"></view>
    <view class="equ_box" @tap="show_equ=true">
      <view class="equ_left">
        <view class="equ_top">油品</view>
        <view class="equ_bottom">￥{{goodData.goods.price}}/升</view>
      </view>
      <view class="equ_rigth">
        <view class="equ_top">{{goodData.name}} {{goodData.show_good}}</view>
        <view class="equ_bottom" style="text-align:right">共计：{{goodData.unit}}升</view>
      </view>
      <view class="icon">
        <AtIcon value='chevron-right' size='24' color='#aaa' style="margin-top:18px"></AtIcon>
      </view>
    </view>
    <view class="input_price">
      <view class="input_label">买单金额</view>
      <view class="input_value" @tap="show_keyboard=true">￥{{inputPrice}}</view>
    </view>
    <view class="qrcode_line">
      <view class="qrcode_title">二维码</view>
      <view class="qrcode_box">
        <Canvas id="myQrcode" canvasId="myQrcode"></Canvas>
      </view>
      <view v-if="showLoading" style="text-align:center">
        <AtActivityIndicator class="qrcode_loading" :isOpened="showLoading"></AtActivityIndicator>
        <text class="qrcode_complated">{{loadingText}}</text>
      </view>
      <view class="qrcode_complated" v-if="showComplated">
        支付成功
      </view>
    </view>
    <view class="bottom_line">
      <view class="price">￥{{inputPrice}}</view>
      <view class="submit" @tap="getQrcode">生成二维码</view>
      <!-- <view class="submit" @tap="createQrcode2">生成二维码</view> -->
    </view>
    <AtFloatLayout :isOpened="show_equ" title="选择油枪" :onClose="handleCloseEqu">
      <view class="equ_line">
        <view class="equ_item" v-for="(item,index) in equList" :key="index" @tap="selectEqu(index)">
          <view class="equ_name">
            <text class="equ_name_number">{{item.show_num}}</text>号油枪
          </view>
          <view class="equ_good">
            <text class="equ_name_number">{{item.goods.name}}</text>
            {{item.goods.type.name}}
          </view>
        </view>
      </view>
    </AtFloatLayout>
    <AtFloatLayout :isOpened="show_keyboard" :onClose="onCloseInput">
      <key-board @onCloseInput="onCloseInput" @onUpdateInput="onUpdateInput"></key-board>
    </AtFloatLayout>
    <AtToast :isOpened="resError" :text="resErrorMsg"></AtToast>
  </view>
</template>

<script>
import Taro from '@tarojs/taro'
import './quickBill.module.scss'
import KeyBoard from "../../components/myKeyboard"
import orderAPI from '../../api/order.js'
import order from '../../api/order.js'
// import QRCode from 'qrcode'
import drawQrcode from 'weapp-qrcode';
import { Canvas } from '@tarojs/components';
// Taro.onAppShow(()=>{
//   console.log("onshow !")
// })
// Taro.onAppHide(() =>{
//   console.log('销毁1')
// })
export default {
  name: 'quickBill',
  components: {
    KeyBoard,Canvas
  },
  data(){
    return{
      equList: [], // 油枪列表
      goodData: {
        name: "",
        unit: 0,
        show_good: "",
        goods_id: "",
        goods:{
          price: "",
          type: {
            neme: ""
          }
        }
      }, // 选择的油枪，油品信息
      show_equ: false, // 显示选择油枪弹窗
      show_keyboard: false, // 显示键盘
      firstIn: true, // 第一次加载进来 选择油枪后弹出键盘
      inputPrice: "0", // 键盘输入的价格
      qrcodeSn: "", // 二维码编号 用于查询状态
      loadingText: "", // loading文本
      showLoading: false, // 显示等待二维码loading
      showComplated: false, // 显示已完成状态
      resError: false, // 接口返回错误
      resErrorMsg: "", // 接口返回错误信息
      stopInterval: true, // 退出页面时停止轮询订单状态接口
    }
  },
  mounted(){
    this.init();
  },
  methods:{
    init(){
      this.getEquList();
      this.stopInterval = false;
    },
    // 获取油枪列表
    async getEquList(){
      var data = {
        app_id: Taro.getStorageSync('app_id'),
        limit: 20,
        page: 1
      }
      const res = await orderAPI.equipmentList(data);
      this.equList = res.data;
      this.equList.forEach(item => {
        item.show_good = item.goods.name + item.goods.type.name;
        item.show_num = parseInt(item.name);
        item.selected = false;
      })
      this.show_equ = true;
    },
    // 选择油枪
    selectEqu(i){ // 选择油枪
      this.goodData = Object.assign({},this.equList[i]);
      this.show_equ = false;
      this.computeUnit();
      if(this.firstIn){
        this.show_keyboard = true;
        this.firstIn = false;
      }
    },
    // 关闭选择油枪
    handleCloseEqu(){
      this.show_equ = false;
    },
    // 计算升数
    computeUnit(){
      if(this.goodData.goods.price != ""){
        this.goodData.unit = (Number(this.inputPrice) / Number(this.goodData.goods.price)).toFixed(2);
      }
    },
    onCloseInput(){  // 关闭数字键盘弹窗
      this.show_keyboard = false;
    },
    onUpdateInput(val){  // 更新输入的金额
      this.inputPrice = val;
      this.computeUnit();
    },
    // 获取二维码
    async getQrcode(){
      this.showLoading = true;
      this.showComplated = false;
      this.loadingText = "正在生成二维码..."

      const sys = await Taro.getSystemInfo();
      const scale = sys.screenWidth / 375;
      
      
      var data = {
        app_id: Taro.getStorageSync('app_id'),
        money: this.inputPrice,
        room_id: Taro.getStorageSync('store_id'),
        cate_id: this.goodData.id
      }
      console.log('获取二维码',data)
      const res = await orderAPI.createQrcodeOrder(data);
      if(res.code == 200){
        this.qrcodeSn = res.data.sn
        drawQrcode({
          width: 240 * scale,
          height: 240 * scale,
          canvasId: 'myQrcode',
          text: res.data.url
        });
        this.loadingText = "正在等待用户扫码..."
        // QR.draw(res.data.url, "cav-qrcode", () => {
        //   console.log('draw success!')  
        //   this.loadingText = "正在等待用户扫码..."
        // })
      }else{
        this.resError = true;
        this.resErrorMsg = res.msg;
        setTimeout(() => {
          this.resErrorMsg = "";
          this.resError = false;
        }, 3000);
      }
      setTimeout(() => {
        this.getOrderStatus();
      }, 2000);
    },
    async getOrderStatus(){
      let pageRoute = Taro.getCurrentPages();
      console.log(pageRoute[pageRoute.length-1].route);
      if(pageRoute[pageRoute.length-1].route == "pages/quickBill/quickBill"){
        var data = {
          app_id: Taro.getStorageSync('app_id'),
          sn: this.qrcodeSn
        }
        const res = await orderAPI.checkQrcodeOrder(data);
        if(res.code == 200){
          if(res.data.status == 2){
            this.showLoading = false;
            this.showComplated = true;
          }else {
            if(res.data.status == 1){
              this.loadingText = "已扫码，等待用户支付..."
            }
            setTimeout(() => {
              this.getOrderStatus();
            }, 3000);
          }
        }
      }else{
        console.log('clear?')
        QR.clear("cav-qrcode", () => {
          console.log('clear success!')  
        })
      }
    },
    async createQrcode2(){
      console.log('生成二维码')
      const sys = await Taro.getSystemInfo();
      const scale = sys.screenWidth / 375;
      drawQrcode({
        width: 240 * scale,
        height: 240 * scale,
        canvasId: 'myQrcode',
        text: 'https://www.baidu.com'
      });
      console.log('生成二维码end')
    }
  },
}
</script>
